/* eslint-disable no-unused-expressions */
import { PlusOutlined } from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Divider, Drawer, message, Modal } from 'antd';
import type { SorterResult } from 'antd/es/table/interface';
import React, { useRef, useState } from 'react';
import type { TenantAddItem, TenantTableListItem } from './data';
import { addTenant, queryTenantDetail, queryTenantList, removeTenant } from './service';
import AddFrom from './components/AddForm';
import TenantDetail from './components/TenantDetail';
import { SUCCESS_CODE } from '@/utils/request';

const TenantTableList: React.FC = () => {
  const [ sorter, setSorter ] = useState<string>('');
  const [ addModalVisible, handleAddModalVisible ] = useState<boolean>(false);
  const [ detailVisible, setDetailVisible ] = useState<boolean>(false);

  const [ selected, setSelected ] = useState<TenantTableListItem | undefined>(undefined);

  const actionRef = useRef<ActionType>();

  async function handleAdd(fields: TenantAddItem) {
    const hide = message.loading('正在添加');

    const res = await addTenant(fields);
    hide();
    if (res.code === SUCCESS_CODE) {
      message.success(res.message || '添加成功');
      actionRef.current?.reload();
    } else {
      message.error(res.message || '添加失败请重试！');
    }
    handleAddModalVisible(false);
    return true;
  }

  // 删除
  const handleRemove = async (fields: { id: string }) => {
    const hide = message.loading('正在删除');
    try {
      await removeTenant(fields);
      hide();
      message.success('删除成功');
      actionRef.current?.reload();
      return true;
    } catch (error) {
      hide();
      message.error('删除失败请重试！');
      return false;
    }
  };
  const columns: ProColumns<TenantTableListItem>[] = [
    {
      title: '客户编号',
      dataIndex: 'id',
      hideInSearch: true,
    },
    {
      title: '客户名称',
      dataIndex: 'name',
    },
    {
      title: '操作',
      render: (_, record) => {
        const onClickDetail = () => {
          setDetailVisible(true);
          setSelected(record);
        };

        const onClickRemove = () => {
          const { id, name } = record;
          Modal.confirm({
            title: `删除客户 ${ id }`,
            content: (
              <>
                <Divider />
                <p>确认要删除客户</p>
                <span>{ name }</span>?
              </>
            ),
            okText: '确定',
            cancelText: '取消',
            onOk: async () => {
              await handleRemove({ id });
            },
          });
        };

        return (
          <div>
            <a onClick={ onClickDetail }>详情</a>
            <Divider type='vertical' />
            <a onClick={ onClickRemove }>删除</a>
          </div>
        );
      },
    },
  ];

  return (
    <PageHeaderWrapper title='客户管理'>
      <ProTable<TenantTableListItem>
        headerTitle={ '客户管理' }
        actionRef={ actionRef }
        rowKey='id'
        onChange={ (_, _filter, _sorter) => {
          const sorterResult = _sorter as SorterResult<TenantTableListItem>;
          if (sorterResult.field) {
            setSorter(`${ sorterResult.field }_${ sorterResult.order }`);
          }
        } }
        params={ {
          sorter,
        } }
        toolBarRender={ () => [
          <Button type='primary' onClick={ () => handleAddModalVisible(true) }>
            <PlusOutlined /> 添加
          </Button>,
        ] }
        tableAlertRender={ () => false }
        request={ (params = {}) => {
          return queryTenantList(params);
        } }
        columns={ columns }
        rowSelection={ false }
      />
      <AddFrom
        modalVisible={ addModalVisible }
        onSubmit={ (value) => handleAdd(value) }
        onCancel={ () => handleAddModalVisible(false) }
      />
      <Drawer
        visible={ !!selected && detailVisible }
        onClose={ () => setDetailVisible(false) }
        width='30%'
      >
        { !!selected && detailVisible && (
          <TenantDetail tenant={ selected } request={ (id) => queryTenantDetail({ id }) } />
        ) }
      </Drawer>
    </PageHeaderWrapper>
  );
};

export default TenantTableList;
